﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Services;
using System.Data.Services.Common;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel.Web;
using System.Text;

namespace PersonaliiService
{
	public class PersonaliiService : DataService<PersonalizationEntities>
	{
		public static void InitializeService(DataServiceConfiguration config)
		{
			config.SetEntitySetAccessRule("*", EntitySetRights.All);
			config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
			config.UseVerboseErrors = true;
			config.DataServiceBehavior.AcceptProjectionRequests = true;
			config.DataServiceBehavior.AcceptCountRequests = true;
			config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
		}

		protected override void HandleException(HandleExceptionArgs args)
		{
			args.UseVerboseErrors = true;
			base.HandleException(args);
		}

		[WebGet]
		public IEnumerable<Employee> GetEmployeesByCommand(string sqlCommand)
		{
			return CurrentDataSource.ExecuteStoreQuery<Employee>(sqlCommand);
		}

		[WebGet]
		public IEnumerable<Organization> GetOrganizationsByCommand(string sqlCommand)
		{
			return CurrentDataSource.ExecuteStoreQuery<Organization>(sqlCommand);
		}

		[WebGet]
		public void FullDeleteNote(int noteId)
		{
			Note note =
				CurrentDataSource.Note.Where(x => x.Id == noteId).SingleOrDefault();

			if(note == null)
				return;

			CurrentDataSource.LoadProperty(note, x => x.EmployeeNoteLink);

			foreach(EmployeeNoteLink link in note.EmployeeNoteLink)
				CurrentDataSource.DeleteObject(link);

			CurrentDataSource.DeleteObject(note);

			CurrentDataSource.SaveChanges();
		}

		[WebGet]
		public void FullDeleteEmployee(int employeeId)
		{
			Employee employee =
				CurrentDataSource.Employee.Where(x => x.Id == employeeId).SingleOrDefault();

			if (employee == null)
				return;

			CurrentDataSource.LoadProperty(employee, x => x.EmployeeNoteLink);

			foreach (EmployeeNoteLink link in employee.EmployeeNoteLink)
				CurrentDataSource.DeleteObject(link);

			CurrentDataSource.LoadProperty(employee, x => x.ConnectionJobEmplDep);

			foreach (ConnectionJobEmplDep link in employee.ConnectionJobEmplDep)
				CurrentDataSource.DeleteObject(link);

			CurrentDataSource.DeleteObject(employee);

			CurrentDataSource.SaveChanges();
		}

		protected override void OnStartProcessingRequest(ProcessRequestArgs args)
		{
			Debug.WriteLine("Start request: {0}", args.RequestUri);
			base.OnStartProcessingRequest(args);
		}
	}
}
